package com.mydemo.admin.controller;

import com.mydemo.common.annotation.Log;
import com.mydemo.common.penum.BusinessType;
import com.mydemo.common.pojo.Option;
import com.mydemo.admin.pojo.SysMenu;
import com.mydemo.admin.service.ISysMenuService;
import com.mydemo.common.pojo.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Last_Island
 * @version 1.0
 */
@RestController
@RequestMapping("/menu")
public class SysMenuController extends BaseController{
    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 获取路由
     * @return
     */
    @GetMapping("/router")
    public RespResult getRouter(){
        Long roleId = getLoginUser().getSysUser().getRoleId();
        return RespResult.defaultSuccess(sysMenuService.getRouter(roleId));
    }

    /**
     * 获取菜单列表
     * @param sysMenu
     * @return
     */
    @PreAuthorize("@authz.decide('system:menu:list')")
    @GetMapping("/list")
    public RespResult getList(SysMenu sysMenu){
        List<SysMenu> menuList = sysMenuService.getMenuList(sysMenu);
        return getTabData(menuList);
    }

    /**
     * 获取菜单树形选项
     * @return
     */
    @GetMapping("/tree")
    public RespResult getTree(){
        Option tree = sysMenuService.getTree();
        return RespResult.defaultSuccess(tree);
    }

    /**
     * 添加菜单
     * @param sysMenu
     * @return
     */
    @PreAuthorize("@authz.decide('system:menu:add')")
    @PostMapping
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    public RespResult addMenu(@RequestBody SysMenu sysMenu){
        return sysMenuService.addMenu(sysMenu) ? RespResult.defaultSuccess() : RespResult.defaultError();
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @PreAuthorize("@authz.decide('system:menu:del')")
    @DeleteMapping("/{id}")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    public RespResult deleteMenu(@PathVariable("id") Long id){
        return sysMenuService.deleteMenu(id) ? RespResult.defaultSuccess() : RespResult.defaultError();
    }

    /**
     * 修改菜单
     * @param sysMenu
     * @return
     */
    @PreAuthorize("@authz.decide('system:menu:update')")
    @PutMapping
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    public RespResult updateMenu(@RequestBody SysMenu sysMenu){
        return sysMenuService.updateMenu(sysMenu) ? RespResult.defaultSuccess() : RespResult.defaultError();
    }

    /**
     * 根据id获取菜单
     * @param id
     * @return
     */
    @PreAuthorize("@authz.decide('system:menu:get')")
    @GetMapping("/{id}")
    public RespResult getMenuById(@PathVariable("id") Long id){
        SysMenu sysMenu = sysMenuService.getMenuById(id);
        return sysMenu == null ? RespResult.defaultError() : RespResult.defaultSuccess(sysMenu);
    }
}
